<template>
  <NavBar title="修改头像昵称"></NavBar>
  <div style="padding: 0 30rpx;">
    <van-cell-group :border="false">
      <van-cell size="large" :border="false">
        <template #title>
          <div class="cellTitle">头像</div>
        </template>
        <template #right-icon>
          <button class="userLogoBtn" style="color:transparent" open-type="chooseAvatar" @chooseavatar="chooseAvatar">
            <img class="userLogo" v-if="userInfo.avatarUrl" :src="userInfo.avatarUrl" alt="">
            <img v-else class="userLogo"
              src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2F12f18496-3075-4367-b599-ae390f0e0b37%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1689920766&t=f9ab93761a45c2449f6bfda2524f0f47"
              alt="">
          </button>
        </template>
      </van-cell>

      <van-cell title="昵称" :border="false">
        <template #right-icon>
          <div style="padding-right: 20rpx;">
            <input v-model="form.nickName" @change="handleInput" class="userNickname" type="nickname" placeholder="请输入昵称">
          </div>
        </template>
      </van-cell>


      <van-button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" v-if="!userInfo?.isBindPhone">
        <van-cell title="绑定手机号" value="点击绑定" :border="false" />
      </van-button>
      <van-button v-else>
        <van-cell title="绑定手机号" :value="userInfo?.email" :border="false" />
      </van-button>

      <van-cell title="绑定微信号" @click="bindWechat" :border="false">
        <template #right-icon>
          <div class="bind" :class="{ bindin: !isBind }">
            {{ isBind ? '已绑定' : '点击绑定' }}
          </div>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
  <van-toast id="van-toast" />
</template>
<script setup>
import NavBar from '@/components/NavBar/index.vue';
import { getUserInfo, updateBaseUserInfo, wxMiniGetPhoneNumber, phoneBindMiniWxByCode } from '@/api/login';
import { useUserStore } from '@/store/modules/user/index.js';
import Toast from '@vant/weapp/dist/toast/toast';
import { getToken } from '@/utils/auth';
import config from '@/config/config.json'
import { ref, onMounted, computed } from 'vue'


const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo)
const form = ref({
  file: uni.getStorageSync('file') || null,
  nickName: null,
  unionId: userStore.userInfo.unionId
})

console.log(userInfo.value);
const isBind = computed(() => {
  if (userInfo.value.unionId) {
    return true
  } else {
    return false
  }
})

onMounted(() => {
  getUserInfoMethods()
})

const getUserInfoMethods = async () => {
  let userObj = await userStore.getUserInfo();
  form.value.nickName = userObj.nickname
  // userInfo.value = res.data

}

const handleInput = async (e) => {
  form.value.nickName = e.detail.value
  const { nickName, unionId } = form.value
  await updateBaseUserInfo({ nickName, unionId })
  Toast.success('修改昵称成功')
}
const chooseAvatar = (e) => {
  console.log(e.detail.avatarUrl);
  uni.setStorageSync('file', e.detail.avatarUrl)
  form.value.file = e.detail.avatarUrl
  uploadFile()
}
const uploadFile = async () => {
  console.log(form.value, '123123');
  let res = await uni.uploadFile({
    url: `${config.siteDomain}${import.meta.env.VITE_GLOB_API_URL}/weixin/uploadUserInfo`,
    filePath: form.value.file,
    name: 'file',
    header: {
      'Content-Type': 'multipart/form-data',
      satoken: getToken()
    },
    formData: form.value,
  })
  res = JSON.parse(res.data)
  Toast.success(res.message)
  getUserInfoMethods()
}

const getPhoneNumber = async (e) => {
  try {
    console.log(e, '手机号');
    form.value.code = e.detail.code
    PutUserInfo()
  } catch (e) {
    console.log(e);
  }
}

const PutUserInfo = async () => {
  console.log(form.value);
  const res = await wxMiniGetPhoneNumber(form.value)
  Toast.success(res.message)
  getUserInfoMethods()
}

const bindWechat = () => {
  uni.login({
    "provider": "weixin",
    "onlyAuthorize": true, // 微信登录仅请求授权认证
    success: async (event) => {
      const { code } = event
      //客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
      const res = await phoneBindMiniWxByCode(code)
      userStore.getUserInfo()
      Toast.success('绑定成功')
      userStore.userInfo = Object.assign(userStore.userInfo, {
        openId: res.data.openid,
        unionId: res.data.unionid
      })
    }
  })
}

</script>
<style lang="less" scoped>
::v-deep {
  .van-cell {
    background-color: var(--a-main-box-bg-color);
    color: var(--a-one-text-color);
  }

  .van-cell-group {
    // padding: 0 45rpx;
    border-radius: 30rpx;
    overflow: hidden;
  }



  .van-cell-group .van-button {
    display: block;
    text-align: left;
    border: none;
    padding: 0;
    height: auto;
    background-color: transparent;

    & .van-cell__value {
      color: var(--a-two-text-color);
    }
  }
}

.cellTitle {
  line-height: 100rpx;
  color: var(--a-one-text-color);
}

.userLogoBtn {
  height: 100rpx;
  background-color: transparent;
  padding: 0 14rpx 0 0;
}

.userLogoBtn::after {
  border: none;
}

.userLogo {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
}

.userNickname {
  text-align: right;
  padding-right: 14rpx;
  color: var(--a-two-text-color);
}

.bind {
  color: var(--a-two-text-color);
}

.bindin {
  color: var(--a-main-color);
}
</style>